<?php
namespace control;
/*
*单据标签类
*/


class orderTagClass extends adIndexClass
{
    private const title = '单据标签';
    private const page = 'orderTag';
    private const table = 'tag';

    /**
     * 获取标签名称
     * @param $id
     * @return string
     */
    public static function getTagName($id): string
    {
        $tags = '';
        $kehu_label = find(array('table' => 'kehu_label', 'where'=>"targetId = '$id' order by list asc"));
        foreach ($kehu_label['array'] as $val) {
            $tag_detail = query('tag_detail', "id = '$val[tag_detail_id]'");
            $tags .= "<span class='background-color-gray' style='margin-right: 5px'>{$tag_detail['name']}</span>";
        }
        return $tags;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('orderTag.home.labelGroup') => text(array("name" => "name")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*客户列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);

        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{})\" class='spanButton'>".lang('materialAttr.homeSearch.new')."</span>\n ";

        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".lang('materialAttr.homeSearch.del')."</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "name" => $this->post('name'),//标签
        );
        //全等查询数组
        $equal = array(
            'coid'=>self::$coid
        );

        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal))." and type=2";
        $page = $this->page(array("table" => self::table, "where" => $where, 'pageNum' => 5, "order" => "time desc"));
        //获取表头
        //获取记录
        $html = "<ul class='tag-list-ul'>";
        $root = root;
        foreach ($page['array'] as $array) {
            $creatName = self::findStaff($array['stid']);
            $detail_html = '';
            $mxResult = find(array('table'=>self::table.'_detail','where'=>"orderId = '$array[id]' order by list asc"));
            foreach ($mxResult['array'] as $val){
                $detail_html.=<<<eee
<li class="background-color-gray">{$val['name']}</li> 
eee;
            }

            $html .= <<<efo
<li>
     <div class="tag-contain">
           <div class="tag-contain-title">
                 <input name="listId[]" type="checkbox" value="$array[id]">
                 <span class="tag-contain-title-text">{$array['name']}</span>
           </div>
           <div class="tag-contain-body">
                 <ul class="tag-contain-ul">
                     {$detail_html}
                 </ul>
           </div>
           <div class="tag-contain-foot">
                <span>{$creatName}</span>
                <span>{$array['time']}</span>
           </div>
           <div class="tag-edit-content">
                <img alt="" onclick="layer('orderTag','operate',{act:'del',id:'{$array['id']}'})" src="{$root}img/control/delete.svg">
                <img onclick="layer('orderTag','edit',{id:'{$array['id']}'})" alt="" src="{$root}img/control/edit.svg">
           </div>
     </div>
</li>
efo;

        }
        $html .= <<<efo
</ul>
<style>
.tag-list-ul{display: inline-flex}
.tag-list-ul>li{float: left;margin: 0 10px 10px 0;}
.tag-contain{width: 300px;height: 400px;padding: 10px;border: 1px solid #d7d7d7;border-radius: 2px}
.tag-contain-title-text{margin-left: 10px;font-weight: bold;font-size: 14px}
.tag-contain-body{margin: 10px;padding: 10px;height: 250px;overflow: auto}
.tag-contain-ul li{float: left;margin: 10px 5px}
.tag-contain-foot{margin: 10px;padding: 10px;border-bottom: 1px solid #d7d7d7}
.tag-contain-foot span:nth-child(2){float: right}
.tag-edit-content{text-align: right}
.tag-edit-content img:nth-child(2){width: 20px;cursor: pointer}
.tag-edit-content img:nth-child(1){width: 22px;cursor: pointer}
}
</style>
<script>
//展示输入框
function showInput(e){
    let id = $(e).parent().parent().parent().parent().find("input[name='attrId[]']").val();
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=showInput',{id:id},function (res){
        $(e).parent().before(res.html);
        $(e).css('display','none');
    },'json')
}
//展示添加按钮
function showAddButton(e){
    let val = e.value;
    let id = $(e).parent().parent().parent().parent().find("input[name='attrId[]']").val();
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=showAddButton',{id:id,val:val},function (res){
        $(e).parent().after(res.html);
        $(e).parent().remove();
        $(".add-attr-button").css('display','inline-flex');
    },'json')
}
function del_this(e){
    $(e).parent().remove();
}
</script>
efo;

        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $html . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 显示输入框
     */
    public function showInput(): bool|string
    {
        $json['html'] = <<<efo
<li><input name="label_name[]" type="text" onblur="showAddButton(this)" value=""></li>
efo;
        return json_encode($json, 320);
    }

    /**
     * 显示添加按钮
     * @return bool|string
     */
    public function showAddButton(): bool|string
    {
        $val = $this->post('val');//值
        $json['html'] = '';
        if (!empty($val)) {
            $mxId = self::getId();
            $json['html'] = <<<efo
<li><span class='background-color-gray li-ico'>{$val}<input name='labelId[]' type='hidden' value='{$mxId}'><input name='label_name[]' type='hidden' value='{$val}'></span><a onclick='del_this(this)'><div><span class='u-icon-delete'><i></i></span></div></a></li>
efo;
        }
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->post('id')?:suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $mxResult = find(array('table' => self::table . '_detail', 'where' => "orderId = '$info[id]'"));
        $label = "<ul class='label-edit-ul addAttr'>";
        foreach ($mxResult['array'] as $val) {
            $label .= "<li><span class='background-color-gray li-ico'>{$val['name']}<input name='labelId[]' type='hidden' value='{$val['id']}'><input name='label_name[]' type='hidden' value='{$val['name']}'></span><a onclick='del_this(this)' href='javascript:void(0)'><div><span class='u-icon-delete'><i></i></span></div></a></li>";
        }
        $label .= "<li><div class='add-attr-button' onclick=\"showInput(this)\">+</div></li></ul>";
        $html = $this->layerEdit(array("table" => array(
            array(
                must . lang('orderTag.home.labelGroup')."：" => text(array("name" => "name", "class" => "text", "value" => $info['name'])),
            ),
            array(
                must . lang('orderTag.edit.edit')."：" => $label,
            ),
        )));


        return $this->layer(array("title" => lang('orderTag.home.title'), "height" => 250, "width" => 800, "html" => $html));
    }


    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $label_name = $this->post('label_name');
        $label_id = $this->post('labelId');
        $field = [
            "name" => $this->post('name'),//联系人姓名
        ];
        $annotation = [
            'name' => lang('orderTag.home.labelGroup'),
        ];
        $rules = [
            'name' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = lang('orderTag.editEdit.power');
        }elseif(empty($label_id) || !is_array($label_id)){
            $json['warn'] = lang('orderTag.editEdit.atLeastOne');;
        } elseif (static::total(array('table' => self::table, 'where' => "name = '$field[name]' and type=2 and coid = '".self::$coid."'  and id !='$id'")) > 0) {
            $json['warn'] = lang('orderTag.editEdit.repeat');;
        }else {
            $isPass = true;
            $this->startTrans();
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'type'=>2,
                    'coid'=>self::$coid,
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "where" => $where,
                    "field" => $field,
                ]);
            }
            foreach ($label_id as $k=>$mxId){
                $mx = query(self::table.'_detail',"id = '$mxId'");
                if (empty($mx['id'])){
                    $warn = static::insert(["table" => self::table.'_detail', "field" => [
                        'id'=>$mxId,
                        'orderId'=>$id,
                        'coid'=>self::$coid,
                        'name'=>$label_name[$k],
                        'time'=>$this->time,
                    ]]);
                    if ($warn !='新增成功'){
                        $json['warn'] = $warn;
                        $isPass = false;
                        break;
                    }
                }
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                $this->commitTrans();
                delete(array('table'=>self::table.'_detail','where'=>"id not in ('".implode("','",$label_id)."') and orderId = '$id'"));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}','{{title}}','{{id}}'], [$this->control['name'],$type,lang('orderTag.home.title'),$id], lang('orderTag.editEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }else{
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = lang('orderTag.operate.delWarn');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], lang('orderTag.operate.delPowerWarn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = lang('orderTag.del.power');
        } elseif (empty($array)) {
            $json['warn'] = lang('orderTag.del.noChoice');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if (static::total(array('table'=>'kehu_label','where'=>"tagId = '$id'"))) {
                    //返回
                    $warn = lang('orderTag.del.used');
                } else {
                    delete(array("table" => self::table.'_detail', "where" => " orderId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = lang('orderTag.del.success');
                    $x++;
                }
                $text .= str_replace(['{{title}}','{{id}}','{{warn}}'], [lang('orderTag.home.title'),$info['id'],$warn], lang('orderTag.del.logFront')). "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}','{{title}}'], [$this->control['name'],lang('orderTag.home.title')], lang('orderTag.del.logCenter')). "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}','{{title}}'], [$x,lang('orderTag.home.title')], lang('materialAttr.del.log'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
    /**
     * 选择分类
     */
    public function warehouse(): bool|string
    {
        $all = self::getDepartmentAll();
        $search = '<i class="container-warehosue-search-ico"></i>' . text(["name" => 'name', 'title' => lang('orderTag.warehouse.searchType'), 'class' => 'container-left-search width300', 'keyup' => 'search_left']);
        $html = <<<efo
                    <div class="container-warehosue paper-content-block" id="container-warehosue" style="position: relative">
                      {$search}
                       {$all}
                    </div>
efo;
        return $this->layer(array("title" => lang('orderTag.warehouse.choiceType'), "height" => 350, "zindex" => 3, "html" => $html, "button" => false));
    }
    /**
     * 左侧搜索框
     *
     * @return string
     */
    public function getContainerLeftJson(): string
    {
        $option['click'] = "replaceDetail($(this).parent(),'" . self::page . "')";
        $json['html'] = self::getDepartmentAll($option);
        return json_encode($json, 320);
    }
    public static function getDepartmentAll($data = []): string
    {
        // 条件
        $data['where'] = $data['where'] ?? "pid='0'";
        // 点击事件
        $data['click'] = $data['click'] ?? "replaceDetail($(this).parent(),'" . self::page . "')";
        // 结果
        $result = find(['table' => 'warehouse_type', 'where' => $data['where'] . " and coid = '".self::$coid."' order by list asc"]);
        $style = ($data['where'] == "pid='0'") ? '' : ' class="child-node"';
        $temp = "<ul {$style} {$data['where']}>";


        if ($result['array']) {
            foreach ($result['array'] as $value) {
                // 角标
                $arrow = "<span class='arrow'  onclick=\"{$data['click']}\"></span>";
                // 判断下级是否存在
                $data['where'] = " pid='{$value['id']}' ";
                $has = query('warehouse_type', $data['where']);
                if ($has['id']) {
                    $temp .= "<li class='arrow-li' title='双击选择' data-id='{$value['id']}' data-name='{$value['name']}'  ondblclick='chooseMaterialType(this)' >{$arrow}{$value['name']}</li>";
                    $temp .= self::getDepartmentAll($data);
                } else {
                    $temp .= "<li class='arrow-no-li' title='双击选择'  data-id='{$value['id']}' data-name='{$value['name']}' ondblclick='chooseMaterialType(this)' onclick=\"{$data['click']}\">{$value['name']}</li>";
                }
            }
        }
        $temp .= '</ul>';
        return $temp;
    }

    /**
     * 批量添加标签
     */
    public function batchAddTags(): bool|string
    {
        $cla         = self::page;
        $label_group = find(array('table' => 'tag', 'where' => "type=2 and coid = '" . self::$coid . "' order by time asc"));
        $group_li    = '';
        foreach ($label_group['array'] as $array) {
            $group_li     .= "<li>{$array['name']}</li><li>";
            $detail_ul    = <<<eof
<ul class="label-content-sec-ul client-level">
eof;
            $label_detail = find(array('table' => 'tag_detail', 'where' => "orderId = '$array[id]' order by list asc"));
            foreach ($label_detail['array'] as $value) {
                $detail_ul .= "<li class='background-color-gray' data-id='{$value['id']}'>{$value['name']}</li>";
            }
            $group_li .= "{$detail_ul}<input name='tagMxId[]' type='hidden' value=''></ul></li>";
        }
        //组合隐藏域
        $hidden = (new materialClass())->combinationHidden($this->post);
        $html = <<<efo
<form name="labelForm">
<div class="label-content">
<ul>
     {$group_li}
</ul>
</div>
<div class="label-footer">
     已选<span id="label-num">0</span>个<span class="del-row-button" id="reset" style="margin-left: 20px">重置</span>
    <span class="spanButton" onclick="$('#{$cla}BatchAddTags').hide()" style="float: right">取消</span>
     <span class="spanButton li-btn-blue-bg" onclick="confirm_batch()" style="float: right">确认</span>
     {$hidden}
</div>
</form>
<style>
.label-content{
   margin: 10px 20px;height: 570px;border-bottom: 2px dashed rgb(215, 215, 215);
}
.label-content-sec-ul li {
  float: left;margin: 10px 5px;text-align: center;cursor: pointer;
}
.background-color-gray{
  margin-left: 0;
}
.label-content>ul>li{
  display: flex;
}
.label-content>ul>li:nth-child(2n+1){
  padding-left: 5px;
  margin-top: 5px;
}
.label-footer{
  height: 50px;
  line-height: 50px;
  margin: 0 20px;
}
</style>
<script>
function confirm_batch(){
     let serialize = $("[name='labelForm']").serialize();
     serialize+='&'+$("[name='listForm']").serialize();
     $('#{$cla}BatchAddTags').hide()
     var obj = event.target;//发生点击事件的当前html节点
     $.post(root+'control/adIndex.html?cla={$cla}&fun=batchAddTagsEdit', serialize, function (data) {
         if (data.warn == 2) {
           if (data.href) {
                //如果异步返回的json参数中定义了重定向url，则跳转到本url
                window.location.href = data.href;
            } else if ($(obj).parents("[searchFormId]").length === 1) {//如果是列表页，则保留查询条件和分页
                //获取查询结果区域的ID号
                var searchFormId = $(obj).parents("[searchFormId]").attr("searchFormId");
                //更新查询结果
                var pageNow = $("[searchformhtml=" + searchFormId + "] > .pageButton .pageNow");//当前页
                if (pageNow.length === 1) {//如果存在分页
                    pageNow.click();
                } else {
                    $("[searchformhtml=" + searchFormId + "]").find("input[type=submit]").click();
                }
                //关闭当前编辑弹窗
                $(obj).parents(".win").find(".winClose").click();
                if (data.msg) {
                    warn(data.msg, 'error');
                }
                if ($.cookie('warn')) {
                    warn($.cookie('warn'));
                    $.cookie('warn', '');
                }
                // 在这里执行需要等待异步请求结束后的代码，函数将会被执行一次，之后就会被销毁
                $(document).one('ajaxStop', function () {
                    initScrollPosition();
                });
            } else if ($("#renovate").attr("url")) {
                //页卡切换时会保存菜单关键字在renovate的url中
                window.location.href = $("#renovate").attr("url");
            } else {
                window.location.reload();
            }
          } else {
            warn(data.warn);
          }
    }, "json");
}
//计算标签数量
 function set_label_num(){
    let num =  $(".label-content-sec-ul .background-color-blue").length;
    $("#label-num").html(num);
 }
 //点击标签
 $(".label-content-sec-ul li").on('click',function() {
     let parent = $(this).parent();
     if ($(this).hasClass('background-color-blue')){
          parent.find("li").removeClass('background-color-blue');
          $(this).siblings("input[name='tagMxId[]']").val('');
     }else{
         parent.find("li").removeClass('background-color-blue');
         $(this).addClass('background-color-blue');
         let id = $(this).data('id');
         $(this).siblings("input[name='tagMxId[]']").val(id);
     }
     set_label_num();
 })
 //重置标签
 $("#reset").on('click',function (){
     $(".label-content-sec-ul").find("li").removeClass('background-color-blue');
     $(".label-content-sec-ul").find("input[type='hidden']").val('');
     set_label_num();
 })
</script>
efo;

        return $this->layer(array("title" => "批量添加标签", "height" => 700, 'button'=>false,"width" => 900, "html" => $html));
    }

    /**
     * 批量添加标签编辑
     */
    public function batchAddTagsEdit(): bool|string
    {
        $table  = $this->post('table');
        $field  = $this->post('field')?:'tags';
        $title  = $this->post('title')?:self::title;
        $page  = self::page;
        if($this->post('page')){
            $page = explode('-',$this->post('page'))[0];
        }

        $listId  = $this->post('listId');
        $tagMxId = $this->post('tagMxId');//标签ID
        if (empty($listId) || !is_array($listId)) {
            $json['warn'] = '您还没有选择单据';
        } elseif (empty($tagMxId) || !is_array($tagMxId)) {
            $json['warn'] = '您还没有选择标签';
        } else {
            $x    = 0;
            $text = '';
            foreach ($listId as $id) {
                $query = query($table, "id = '$id'");
                //其他情况
                if(empty($query['id']) && $table == 'machining_order'){
                    $machining_order_mx = query('machining_order_mx', "id = '$id'");
                    $query = query($table, "id = '$machining_order_mx[orderId]'");
                }
                if(empty($query['id'])){
                    continue;
                }
                $x++;
                $tagsText = '';
                //添加标签
                $kehu_label_id = [];
                foreach ($tagMxId as $tagsId) {
                    $tags_detail = query('tag_detail', "id = '$tagsId'");
                    if ($tags_detail['id']) {
                        $kehu_label = query('kehu_label', "targetId = '$query[id]' and tag_detail_id = '$tagsId'");
                        $tags       = query('tag', "id = '$tags_detail[orderId]'");
                        $tagsText   .= $tags_detail['name'] . ',';
                        if (empty($kehu_label['id'])) {
                            $mid             = self::getId();
                            $kehu_label_id[] = $mid;
                            static::insert(array(
                                'table' => 'kehu_label',
                                'field' => [
                                    'id'            => $mid,
                                    'coid'          => self::$coid,
                                    'targetId'      => $query['id'],
                                    'tag_detail_id' => $tagsId,
                                    'tagId'         => $tags['id'],
                                    'type'          => 2,
                                ],
                            ));
                        } else {
                            $kehu_label_id[] = $kehu_label['id'];
                        }
                    }
                }
                //删除无效关联的标签
                $obj = isset($query['orderNo'])?$query['orderNo']:$query['id'];
                delete(array('table' => 'kehu_label', 'where' => "id not in ('" . implode("','", $kehu_label_id) . "') and targetId = '$query[id]'"));
                update(array('table' => $table, 'field' => [$field => $tagsText], 'where' => "id = '$query[id]'"));
                $text .= $title . "【{$obj}】添加了标签{$tagsText}<br>";
            }
            $this->logText(["type" => $page, "text" => $this->control['name'] . "批量" . $title . "添加标签：" . $text]);
            $json['warn']     = 2;
            $_SESSION['warn'] = '成功给' . $x . '个' . $title . '添加了标签';
        }
        return json_encode($json, 320);
    }

}
